<template>
  <div class="clearfix">
    <a-upload
      name="file"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :action="upload.url + '/common/upload'"
      :before-upload="beforeUpload"
      @change="handleChange"
      style="height: 75px"
      :headers="upload.headers"
    >
      <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="height: 85px" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
  </div>
</template>
<script>
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
export default {
  name: "SysUpload",
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      imageUrl: "",
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        uploadStatus: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + storage.get(ACCESS_TOKEN) },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API,
      },
      data: { companyId: "" },
    };
  },
  methods: {
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        // getBase64(info.file.originFileObj, (imageUrl) => {
        //   this.imageUrl = info.file.response.data.url;
        //   this.loading = false;
        //   this.$emit("input", this.imageUrl);
        // });
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl = info.file.response.data.url;
          this.$emit("input", this.imageUrl);
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("传入JPG/PNG格式的图片");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片不能");
      }
      return isJpgOrPng && isLt2M;
    },
  },
};
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
